
const {readJson,writeJson} = require('../../until/fs');
const {SHOP_JSON,USER_JSON,STORE_ORDER} = require('../../config/config.data');
const uuid = require('node-uuid')

// 获取订单列表
let getBuylist = (req,res) =>{
    const {user} = req.body;

    let orderList = readJson(STORE_ORDER);
        orderList = orderList.filter(item=>item.user === user).map(item=>({
            orderid:item.orderid,
            address:item.address,
            shopName:item.shopName,
            num:item.num,
            appointmentTime:item.appointmentTime,
            appointmentPhone:item.appointmentPhone,
            status:item.status        
    }))

    res.send({code:1,msg:"订单列表请求成功",data:orderList})

}
// 新增订单
let addBuyList = (req,res) =>{
    const {submitData} = req.body;

    // 查询下单用户信息
    let userList = readJson(USER_JSON);
    let userData = userList.find(item=>item.user === submitData.user);
    const {name,sex,cardType,card} = userData;

    // 查询对应门店信息
    let shopList = readJson(SHOP_JSON);
    let shopData = shopList.find(item=>item.shopID === submitData.shopID);
    const {shopName,address} = shopData;

    // 拼合订单数据进行添加
    let addData = {
        ...submitData,
        name,
        sex,
        cardType,
        card,
        shopName,
        address,
        orderid:uuid.v1(),
        status: "ok",
        createTime: new Date().getTime()
    }
    let orderList = readJson(STORE_ORDER);
        orderList.push(addData)

    writeJson(STORE_ORDER,orderList)
    res.send({code:1,msg:"预约成功",data:[]})
 
}

// 取消订单
let cancelBuyList =  (req,res) =>{
    const {orderid} = req.body;
    let orderList = readJson(STORE_ORDER);

    //查找并修改状态
    let index     = orderList.findIndex(item=>item.orderid === orderid) 
    orderList[index].status = 'cancel';
    writeJson(STORE_ORDER,orderList);
    res.send({code:1,msg:"取消成功",data:[]})
}

module.exports = {
    getBuylist,addBuyList,cancelBuyList
}